<template>
  <div style="width:100vw;display:flex;justify-content: center;background:#F9F9F9;flex-direction: column;align-items: center;">
    
    <!-- 面包屑导航栏 -->
    <div style="margin-left:-58%;margin-bottom: -20px;">
    <AppBreadcrumb :breadcrumbs="breadcrumbs" :breadcrumbItemStyle="breadcrumbItemStyle" />
    </div>
    
    <!-- 作业标题和状态 -->
        <div class="assignment-info" @click="navigateToAssignments">
          <img src="@/assets/picture/arrow-left.png" alt="返回" class="arrow-icon" />
          <h2 class="assignment-title">{{ assignmentTitle }}</h2>
          <span class="badge" :class="statusBadgeClass">{{ statusLabel }}</span>
        </div>

    <div class="container" style="width:80vw;display: flex;padding: 20px 0px;justify-content: center;background:#DCE4F5">
      <!-- 返回按钮（上一个） -->
      <div style="display:flex;align-items: center;margin-right:20px">
        <button @click="before" class="back-button">
          <img :src="beforeImg" alt="上一个" class="button-image" />
        </button>
      </div>
      
      <!-- 学生作业详情 -->
      <div class="assignment-details" v-if="assignmentData">
        <!-- 学生头像 -->
        <div style="display: flex; justify-content: center; margin-bottom: 20px;">
          <img :src="studentAvatarUrl" alt="学生头像" style="width: 120px; height: 120px; border-radius: 50%;" />
        </div>
        <div class="detail-container">
            <div class="detail-item">
              <span class="detail-label">学生姓名：</span>
              <span class="detail-value">{{ assignmentData.username }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">提交时间：</span>
              <span class="detail-value">{{ assignmentData.update_time }}</span>
            </div>
            <div class="detail-item vertical">
              <span class="detail-label">作业内容：</span>
              <div class="content" v-html="assignmentData.content"></div>
            </div>
            <div class="detail-item">
              <span class="detail-label">附件：</span>
              <div class="attachment-container">
                <a v-if="assignmentData.attachment_url" 
                   :href="assignmentData.attachment_url" 
                   target="_blank"
                   class="attachment-link">
                   下载附件
                </a>
                <img v-else 
                     src="@/assets/picture/none.png" 
                     class="no-attachment-img" />
              </div>
            </div>
          </div>
      </div>

      <!-- 评阅表单 -->
      <div class="grading-form">
        <form @submit.prevent="submitGrade">
          <label for="each_score" style="display: block; margin-right: 10px;">成绩:</label>
          <div class="form-group" style="display:flex;flex-direction:row;align-items: center;margin-bottom: 30px;margin-top: 10px;">
            <input
              type="number"
              id="each_score"
              v-model.number="formData.each_score"
              required
              min="0"
              max="100"
              style="padding: 10px; border: 1px solid #ccc;"
            />
            <p style="margin-left: 10px;">分</p>
          </div>
          <div class="form-group">
            <label for="each_comment" style="display: block; margin-bottom: 15px;">评语:</label>
            <!-- 使用富文本编辑器替换文本域 -->
            <QuillEditor v-model="formData.each_comment" />
          </div>
          <button type="submit" class="submit-button" style="margin-top: 20px;">提交</button>
        </form>
      </div>

      <!-- 下一个按钮 -->
      <div style="display:flex;align-items: center;margin-left:20px">
        <button @click="next" class="back-button">
          <img :src="nextImg" alt="下一个" class="button-image" />
        </button>
      </div>
    </div>
    
    <div class="container" style="width:80vw;display: flex;flex-direction: column;background:white;margin-bottom: 40px;">
      <h3 style="margin: 20px;">评阅列表</h3>
      
      <!-- 错误提示 -->
      <div v-if="commentsErrorMessage" class="error-message">
        <p>{{ commentsErrorMessage }}</p>
      </div>

      <!-- 评论列表 -->
      <div v-for="(comment, index) in comments" :key="index" class="content-card">
        <strong style="font-size:14px">{{ comment.username }} ({{ getIdentityLabel(comment.identity) }})：</strong>
        <p style="text-indent:30px;padding:10px"  v-html="comment.each_comment"></p>
        <div style="font-size: 12px;margin:0px 20px;display:flex;justify-content: flex-end;">
          <span style="margin:0px 20px;">评论时间: {{ comment.create_time }}</span>
          <span>评阅分数: {{ comment.each_score !== null ? comment.each_score + '分' : '未评分' }}</span>
        </div>
      </div>
      
      <!-- 无评论时的提示 -->
      <div v-if="comments.length === 0 && !commentsErrorMessage" class="no-comments">
        <p>暂无评论</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { fetchStudentAssignmentDetails, fetchComments, submitStudentGrade,fetchClassDetails,fetchAssignmentDetails } from '@/services/api';
import AppBreadcrumb from '@/components/Breadcrumb.vue';
import QuillEditor from '@/components/QuillEditor.vue';
import { ElMessage } from 'element-plus';

// 导入按钮图片
import beforeImgPath from '@/assets/picture/before.png';
import nextImgPath from '@/assets/picture/next.png';

export default {
  name: 'StudentAssignmentReview',
  components: { AppBreadcrumb, QuillEditor },
  props: {
    homeworkId: {
      type: [String, Number],
      required: true,
    },
    stuHmwkId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const route = useRoute();
    const courseName = ref('');
    const assignmentTitle = ref('');
    const techId = ref(null);

    const assignmentData = ref(null);
    const studentName = ref('');
    const breadcrumbItemStyle = ref({
      textDecoration: 'none',
      color: 'gray',
      fontSize: '14px',
    });

    const assignmentStatus = ref(localStorage.getItem('hmk_status') || '新建中');

    const defaultAvatar = require('@/assets/picture/default-avatar.png'); 
    const studentAvatarUrl = ref(defaultAvatar);
    const beforeImg = beforeImgPath;
    const nextImg = nextImgPath;

    const formData = ref({
      each_score: null,
      each_comment: '',
    });
    const errorMessage = ref('');
    const comments = ref([]);
    const commentsErrorMessage = ref('');
    const semesterId = localStorage.getItem("selectedClassId");
    const identity = ref(localStorage.getItem('identity') || null);

    const breadcrumbs = computed(() => [
      
      { path: `/class-management/${props.homeworkId}/TechNoti`, label:courseName.value || '课程' },
      { path: `/class-management/${props.homeworkId}/TechAssignments`, label: '图文作业' },
      { path: `/assignmen-list/${props.homeworkId}/${semesterId}`, label:assignmentTitle.value || '作业详情' },
      { path: route.path, label: studentName.value }
    ]);

    const loadAssignmentDetails = async () => {
      try {
        const response = await fetchStudentAssignmentDetails(props.stuHmwkId);
        if (response.data.status === 1) {
          assignmentData.value = response.data.data;
          studentName.value = response.data.data.username;
          studentAvatarUrl.value = assignmentData.value.img_url || defaultAvatar;
          await loadComments();
        } else {
          errorMessage.value = `获取作业详情失败：${response.data.msg}`;
        }
      } catch (error) {
        errorMessage.value = '加载作业详情失败，请稍后重试。';
      }
    };

    const loadCourseName = async () => {
      const semesterId = localStorage.getItem("selectedClassId")
      const techIdValue = techId.value;

      try {
        const response = await fetchClassDetails(semesterId, techIdValue);
        if (response.data.status === 1) {
          courseName.value = response.data.data.semester_name;
        } else {
          console.error('获取课堂详情失败:', response.data.msg);
        }
      } catch (error) {
        console.error('加载课堂详情失败:', error);
      }
    };

    const loadhmk_title = async () => {
      try {
        const response = await fetchAssignmentDetails(props.homeworkId);
        if (response && response.data && response.data.status === 1 && response.data.data) {
          const data = response.data.data;
          assignmentTitle.value = data.hmk_title || "标题缺失";
        } else {
          console.error("API 返回数据结构不符合预期:", response);
        }
      } catch (error) {
        console.error("获取作业详情请求失败:", error);
      }
    };

    
    const loadComments = async () => {
      try {
        const response = await fetchComments(props.stuHmwkId);
        if (response.data.status === 1) {
          comments.value = response.data.data;
          commentsErrorMessage.value = ''; // 清除错误信息
        } else {
          commentsErrorMessage.value = `获取评论列表失败：${response.data.msg}`;
        }
      } catch (error) {
        commentsErrorMessage.value = '加载评论列表失败，请稍后重试。';
      }
    };

    const submitGrade = async () => {
      try {
        const userId = localStorage.getItem('id');
        if (!userId) {
          ElMessage.error('用户未登录或用户ID不存在，请重新登录。');
          return;
        }
        const currentIdentity = identity.value;
        if (currentIdentity === null) {
          ElMessage.error('无法获取用户身份，请重新登录。');
          return;
        }
        const payload = {
          user_id: userId,
          each_score: formData.value.each_score,
          identity: Number(currentIdentity),
          each_comment: formData.value.each_comment,
        };
        const response = await submitStudentGrade(props.stuHmwkId, payload);
        if (response.data.status === 1) {
          ElMessage.success('评阅成功！');
          await loadAssignmentDetails();
          formData.value.each_score = null;
          formData.value.each_comment = '';
        } else {
          errorMessage.value = `提交评阅失败：${response.data.msg}`;
        }
      } catch (error) {
        errorMessage.value = '提交评阅失败，请稍后重试。';
      }
    };

    const before = () => {
      const prevId = Number(props.stuHmwkId) - 1;
      if (prevId > 0) {
        router.push({
          name: 'StudentAssignmentReview',
          params: { homeworkId: props.homeworkId, stuHmwkId: prevId },
        });
      } else {
        ElMessage.error('已经是第一个学生了！');
      }
    };

    const next = () => {
      const nextId = Number(props.stuHmwkId) + 1;
      router.push({
        name: 'StudentAssignmentReview',
        params: { homeworkId: props.homeworkId, stuHmwkId: nextId },
      });
    };

    // 导航回到图文作业页
    const navigateToAssignments = () => {
     router.push({
        path: `/assignmen-list/${props.homeworkId}/${semesterId}`,});
    };
    // 根据作业状态返回对应的标签
    const statusLabel = computed(() => {
      switch (assignmentStatus.value) {
        case '0':
          return '未发布';
        case '1':
          return '未开始';
        case '2':
          return '进行中';
        case '3':
          return '已截止';
        default:
          return '未知状态';
      }
    });

    // 根据作业状态返回对应的样式类
    const statusBadgeClass = computed(() => {
      switch (assignmentStatus.value) {
        case '0':
          return 'badge-unpublished';
        case '1':
          return 'badge-unstart';
        case '2':
          return 'badge-in-progress';
        case '3':
          return 'badge-closed';
        default:
          return 'badge-new';
      }
    });

    watch(
      () => props.stuHmwkId,
      () => {
        loadAssignmentDetails();
        formData.value.each_score = null;
        formData.value.each_comment = '';
      }
    );

    onMounted(() => {
      techId.value = localStorage.getItem('id'); // 确保 'techId' 已存储在 localStorage 中
      loadCourseName();
      loadhmk_title();
      loadAssignmentDetails()
      });

    const getIdentityLabel = (identity) => {
      switch (identity) {
        case '0': return '学生';
        case '1': return '老师';
        case '2': return '管理员';
        default: return '未知';
      }
    };

    return {
      assignmentData,
      formData,
      submitGrade,
      errorMessage,
      studentAvatarUrl,
      before,
      next,
      beforeImg,
      nextImg,
      identity,
      comments,
      commentsErrorMessage,
      getIdentityLabel,
      breadcrumbs,
      breadcrumbItemStyle,
      navigateToAssignments, // 导航方法
      assignmentTitle,
      statusLabel,
      statusBadgeClass,
    };
  },
};
</script>


<style scoped>
.container {
  width: 100vw;
  background: #F9F9F9;
}
p{
  font-size: 14px;
}

/* 保留您原有的样式 */
.back-button {
  background-color: #DCE4F5;
  padding: 0; /* 移除内边距以适应图片 */
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-bottom: 20px;
  width: 50px; /* 根据图片大小调整宽度 */
  height: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-button:hover {
  background-color: #fff;
}

.button-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.assignment-details {
  background-color: #ffffff;
  padding: 60px 30px;
  border-right: 1px solid rgb(237, 237, 237);
  width: 45%;
}

.grading-form {
  background-color: #ffffff;
  padding: 60px 30px;
  width: 30%;
}

.form-group {
  margin-bottom: 15px;
}

.submit-button {
  background-color: #244382;
  color: #fff;
  padding: 10px 40px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 68%;
}

.submit-button:hover {
  background-color: #3e66b0;
}
.content-card{
  background:#F9F9F9;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin: 20px;
}


.assignment-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0px;
  font-size: 16px;
  cursor: pointer; /* 指针样式，表明可点击 */
  height: 55px;
  width: 80%;
}

.assignment-title {
  font-weight: bold;
  margin-right: 10px;
}

.badge {
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.arrow-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.badge-unpublished {
  background-color: #ffd6d6;
  color: #d9534f;
}

.badge-unstart {
  background-color: #cae2f9;
  color: #519bd5;
}

.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}

.badge-closed {
  background-color: #f0f0f0;
  color: #666;
}

.badge-new{
    background-color: #f3e4b7f0;
  color:  #dda90ff0;
}
.detail-container {
  padding: 20px 50px;
}

.detail-item {
  display: grid;
  grid-template-columns: 100px 1fr;
  align-items: start;
  margin-bottom: 18px;
}

.detail-label {
  font-weight: 600;
  color: #2f57a7;
  font-size: 15px;
}

.detail-value {
  color: #4a5568;
  font-size: 14px;
  word-break: break-word;
}

.content {
  width: 100%;
  padding: 8px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
    margin-top: 5px;
}

.attachment-container {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.attachment-link {
  background: #2f57a710;
  color: #2f57a7;
  padding: 6px 12px;
  border-radius: 4px;
  text-decoration: none;
  transition: background 0.2s;
}

.attachment-link:hover {
  background: #2f57a720;
}

.no-attachment-img {
  width: 90px;
  margin-left: 12px;
  opacity: 0.7;
}
</style>